<%
-- Copyright 2015 OVH (OverTheBox@ovh.net)
-- Simon Lelievre (simon.lelievre@corp.ovh.com)
-- Sebastien Duponcheel (sebastien.duponcheel@ovh.net)
--
-- This file is part of OverTheBox for OpenWrt.
--
--    OverTheBox is free software: you can redistribute it and/or modify
--    it under the terms of the GNU General Public License as published by
--    the Free Software Foundation, either version 3 of the License, or
--    (at your option) any later version.
--
--    OverTheBox is distributed in the hope that it will be useful,
--    but WITHOUT ANY WARRANTY; without even the implied warranty of
--    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--    GNU General Public License for more details.
--
--    You should have received a copy of the GNU General Public License
--    along with OverTheBox.  If not, see (http://www.gnu.org/licenses/)
-%>
<%
-- Copyright 2018-2022 Ycarus (Yannick Chabanois) ycarus@zugaina.org for OpenMPTCProuter
--
-- Small changes to make this work with OpenMPTCProuter
-- New features: 
-- * DNS detection
-- * IPv6 route received
-- * latest version available
-- * MPTCP server status
-- * Server status, errors,icon,...
-- * Many tests
-%>
<%+header%>
<%
local ucic = luci.model.uci.cursor()
local menuentry = ucic:get("openmptcprouter","settings","menu") or "openmptcprouter"
local statuslogo = ucic:get("openmptcprouter","settings","statuslogo") or "openmptcprouter.png"
%>
<link rel="stylesheet" type="text/css" href="<%=resource%>/openmptcprouter/css/wanstatus.css?v=git-20"/>
<script type="text/javascript" src="<%=resource%>/seedrandom.js?v=git-20"></script>
<script type="text/javascript" src="<%=resource%>/cbi.js?v=git-20"></script>
<script type="text/javascript">//<![CDATA[
	var anonymize = false;
	function getCookieValue(a) {
		var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
		return b ? b.pop() : '';
	}
	function testPrivateIP(ip) {
		if ( (/^(10)\.(.*)\.(.*)\.(.*)$/.test(ip)) || (/^(172)\.(1[6-9]|2[0-9]|3[0-1])\.(.*)\.(.*)$/.test(ip)) || (/^(192)\.(168)\.(.*)\.(.*)$/.test(ip)) ){
			return true;
		} else {
			return false;
		}
	}
	function formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"][d]}
	XHR.poll(20, '<%=build_url("admin/system/" .. menuentry:lower() .. "/interfaces_status")%>', null,
		function(x, mArray)
		{
			var status = document.getElementById('openmptcprouter_status');
			var temp = '<figure class="tree">';
			temp += '<ul>';
			if (mArray !== null && mArray.openmptcprouter)
			{
				anonymize=getCookieValue("anonymize");
				if (anonymize == "true")
				{
					mArray.openmptcprouter.wan_addr=replaceLastNChars(mArray.openmptcprouter.wan_addr,"x",6);
					mArray.openmptcprouter.wan_addr6=replaceLastNChars(mArray.openmptcprouter.wan_addr6,"x",10);
					mArray.openmptcprouter.service_addr=replaceLastNChars(mArray.openmptcprouter.service_addr,"x",6);
					document.getElementById("anon").checked = true;
				}
				temp += '<li class="remote-from-lease">';
				temp += '<a href="#">';

				var equipmentIcon = '<img src="<%=resource%>/computer.png" />';
				if (mArray.openmptcprouter.remote_addr)
				{
					if (mArray.openmptcprouter.remote_from_lease == false)
					{
						var title = String.format("%s (%s)",'<%:You%>', mArray.openmptcprouter.remote_addr);
						var statusMessageClass = "warning";
						var statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
						var statusMessage = '<%:Your IP was not leased by this router%>';
					} else {
						var title = String.format('<br /><strong>%s (%s)</strong>', mArray.openmptcprouter.remote_hostname ? mArray.openmptcprouter.remote_hostname : _('<%:You%>'), mArray.openmptcprouter.remote_addr)
						var statusMessageClass = "";
						var statusIcon = "<%=resource%>/openmptcprouter/images/statusOK.png";
						var statusMessage = "";
					}
				} else {
					var title = String.format('<br /><strong>%s</strong>', _('Clients'))
					var statusMessageClass = "";
					var statusIcon = "<%=resource%>/openmptcprouter/images/statusOK.png";
					var statusMessage = "";
				}
				var content = "";

				temp += getNetworkNodeTemplate(equipmentIcon, statusIcon, title, statusMessageClass,statusMessage,content);
				temp += '</a>';

				temp += '<li id="networkRootNode"><table><tr><td><table>';
				if (mArray.wans)
				{
					temp += '<tr class="spaceline"><td></td></tr>';
					for( var j = 1; j < mArray.wans.length; j++ )
					{
						temp += '<tr class="spaceline"><td></td></tr>';
					}
				}
				temp += '<tr><td></td></tr><tr><td><a href="#" id="omr">';
				var equipmentIcon = '<img src="<%=resource%>/<%=statuslogo%>" style:"top: 0px;" />';
				var title = String.format("%s (%s)", mArray.openmptcprouter.hostname, mArray.openmptcprouter.local_addr);
				var statusMessageClass = "";
				var statusIcon = "<%=resource%>/openmptcprouter/images/statusOK.png";
				var statusMessage = "";
				var content = "";

				if (mArray.openmptcprouter.version)
				{
					//content += "Version " + mArray.openmptcprouter.version.replace(/\"/g,'');
					content += "Version " + mArray.openmptcprouter.version;
					if (mArray.openmptcprouter.latest_version_omr != mArray.openmptcprouter.version && mArray.openmptcprouter.latest_version_omr != "")
					{
						content += "<br><i>(" + '<%:Latest available version%>' + " " + mArray.openmptcprouter.latest_version_omr + ")</i>";
					}
					content += "<br />";
				}
				if (mArray.openmptcprouter.loadavg)
				{
					content += '<%:Load:%>' + " " + mArray.openmptcprouter.loadavg;
					content += "<br />";
				}
				if (mArray.openmptcprouter.core_temp)
				{
					content += '<%:Core temp:%>' + " " + (mArray.openmptcprouter.core_temp / 1000).toFixed(1) + " &#176;";
					content += "<br />";
				}
				if (mArray.openmptcprouter.uptime)
				{
					var date = new Date(null);
					content += '<%:Uptime:%>' + " " + String.format('%t', mArray.openmptcprouter.uptime);
					content += "<br />";
				}
				if (mArray.openmptcprouter.dhcpd)
				{
					for ( dhcpd in mArray.openmptcprouter.dhcpd )
					{
						var dhcp = mArray.openmptcprouter.dhcpd[dhcpd];
						content += String.format('<span style="text-transform:capitalize;">%s</span> %s %s<br />', dhcp.interface, '<%:address:%>' ,dhcp.router);
						content += String.format('<span style="text-transform:capitalize;">%s</span> %s %s - %s<br />', dhcp.interface, '<%:range:%>', dhcp.range_start, dhcp.range_end);
					}
				}

				if (mArray.openmptcprouter.shadowsocks_enabled == true && mArray.openmptcprouter.service_addr != "") 
				{
					if (mArray.openmptcprouter.shadowsocks_service == false)
					{
						statusMessage += '<%:ShadowSocks is not running%>';
						if (mArray.openmptcprouter.shadowsocks_service_key == false && mArray.openmptcprouter.shadowsocks_service_method !== "none")
						{
							statusMessage += ' <i>(' + '<%:empty key%>' + ')</i>';
						}
						statusMessage += '<br/>';
					}
				}
				if (mArray.openmptcprouter.v2ray_enabled == true && mArray.openmptcprouter.service_addr != "")
				{
					if (mArray.openmptcprouter.v2ray_service == false)
					{
						statusMessage += '<%:V2Ray is not running%>';
						statusMessage += '<br/>';
					}
				}
				if (mArray.openmptcprouter.fsro == true)
				{
					statusMessage += '<%:Filesystem is readonly%>' + '<br/>';
				}
				if (mArray.openmptcprouter.multi_vpn == true)
				{
					statusMessage += '<%:More than one default VPN is enabled%>' + '<br/>';
				}
				if (mArray.openmptcprouter.tun_service == false && mArray.openmptcprouter.service_addr != "")
				{
					statusMessage += '<%:VPN is not running%>' + '<br/>';
				}
				if (mArray.openmptcprouter.dns == false)
				{
					statusMessage += '<%:DNS issue: can\'t resolve hostname%>' + '<br/>';
				}

				if(statusMessage !== "")
				{
					statusMessageClass = "error";
					statusIcon = "<%=resource%>/openmptcprouter/images/statusError.png";
				} else if (mArray.openmptcprouter.service_addr != "")
				{
					if (mArray.openmptcprouter.v2ray_enabled == false && mArray.openmptcprouter.shadowsocks_enabled == false)
					{
						statusMessage += '<%:Proxy is DISABLED%>' + '<br/>';
					} 
					if (mArray.openmptcprouter.tun_state == "DOWN")
					{
						statusMessage += '<%:VPN tunnel DOWN%>' + '<br/>';
					}
					if (mArray.openmptcprouter.ipv6 == "enabled")
					{
						if (mArray.openmptcprouter.tun6_state == "DOWN")
						{
							statusMessage += '<%:IPv6 tunnel DOWN%>' + '<br/>';
						} else if (mArray.openmptcprouter.wan_addr6 == '')
						{
							statusMessage += '<%:No IPv6 access%>' + '<br/>';
						}
					}
					if (statusMessage !== "")
					{
						statusMessageClass = "warning";
						statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
					}
				}
				temp += getNetworkNodeTemplate(equipmentIcon, statusIcon, title, statusMessageClass,statusMessage,content);
				temp += '</a>';
				temp += '</td></tr>';
				temp += '<tr><td><div class="vertdash" ></div></td></tr>';
				temp += '<tr><td>';
				temp += '<a href="<%=url('admin/system/' .. menuentry:lower() .. '/wizard')%>" id="omr-vps">';
				var statusIcon = "<%=resource%>/openmptcprouter/images/statusOK.png";
				var equipmentIcon = '<img src="<%=resource%>/server.png" />';
				content = "";
				statusMessage = "";
				if ((mArray.openmptcprouter.wan_addr == mArray.openmptcprouter.service_addr || mArray.openmptcprouter.wan_addr == mArray.openmptcprouter.service_addr_ip) && mArray.openmptcprouter.wan_addr != "")
				{
					var title = String.format("%s (%s)", mArray.openmptcprouter.vps_hostname, mArray.openmptcprouter.wan_addr);
				} else if ((mArray.openmptcprouter.wan_addr6 == mArray.openmptcprouter.service_addr || mArray.openmptcprouter.wan_addr6 == mArray.openmptcprouter.service_addr_ip6) && mArray.openmptcprouter.wan_addr6 != "")
				{
					var title = String.format("%s (%s)", mArray.openmptcprouter.vps_hostname, mArray.openmptcprouter.wan_addr6);
				} else if (mArray.openmptcprouter.wan_addr != "" && mArray.openmptcprouter.service_addr == "127.0.0.1")
				{
					var title = String.format("%s (%s)", mArray.openmptcprouter.vps_hostname, mArray.openmptcprouter.wan_addr);
				} else if (mArray.openmptcprouter.wan_addr6 != "" && mArray.openmptcprouter.service_addr == "127.0.0.1")
				{
					var title = String.format("%s (%s)", mArray.openmptcprouter.vps_hostname, mArray.openmptcprouter.wan_addr6);
				} else if (mArray.openmptcprouter.direct_output == false)
				{
					var title = String.format("%s (%s)", mArray.openmptcprouter.vps_hostname, mArray.openmptcprouter.wan_addr6);
				} else if (mArray.openmptcprouter.wan_addr != "" && mArray.openmptcprouter.direct_output == true)
				{
					var title = String.format("%s (%s)", _('Direct output'), mArray.openmptcprouter.wan_addr);
					statusMessageClass = "warning";
					statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
				} else if (mArray.openmptcprouter.wan_addr6 != "" && mArray.openmptcprouter.direct_output == true)
				{
					var title = String.format("%s (%s)", _('Direct output'), mArray.openmptcprouter.wan_addr6);
					statusMessageClass = "warning";
					statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
				} else if (mArray.openmptcprouter.proxy_addr != "" && mArray.openmptcprouter.vps_status != "DOWN")
				{
					var title = String.format("%s (%s)", mArray.openmptcprouter.vps_hostname, mArray.openmptcprouter.proxy_addr);
				} else if (mArray.openmptcprouter.external_check == false) {
					var title = String.format("%s ?", mArray.openmptcprouter.vps_hostname);
				} else {
					var title = '<%:No output%>';
					statusMessage += '<%:No output%>' + '<br/>';
				}
				if (mArray.openmptcprouter.wan_addr == "" && mArray.openmptcprouter.wan_addr6 == "" && mArray.openmptcprouter.proxy_addr == "" && mArray.openmptcprouter.external_check == true)
				{
					statusMessage += '<%:No server IP address, No public IP address%>' + '<br/>';
				}
				if (mArray.openmptcprouter.service_addr !== "" && (mArray.openmptcprouter.wan_addr !== "" || mArray.openmptcprouter.wan_addr6 !== "") && mArray.openmptcprouter.vps_status == "DOWN")
				{
					statusMessage += '<%:Can\'t access and use server part%>' + '<br/>';
				}
				if (statusMessage !== "")
				{
					statusMessageClass = "error";
					statusIcon = "<%=resource%>/openmptcprouter/images/statusError.png";
				}
				if (mArray.openmptcprouter.service_addr == "")
				{
					statusMessage += '<%:No server defined%>' + '<br/>';
				} else {
					if (mArray.openmptcprouter.vps_status == "DOWN")
					{
						statusMessage += '<%:Can\'t ping server%>' + '<br/>';
					} else if (mArray.openmptcprouter.shadowsocks_enabled == true && mArray.openmptcprouter.proxy_addr == "" && mArray.openmptcprouter.external_check == true)
					{
						statusMessage += '<%:Can\'t get public IP address from ShadowSocks%>' + '<br/>';
					} else if (mArray.openmptcprouter.v2ray_enabled == true && mArray.openmptcprouter.proxy_addr == "" && mArray.openmptcprouter.external_check == true)
					{
						statusMessage += '<%:Can\'t get public IP address from V2Ray%>' + '<br/>';
					} else if (mArray.openmptcprouter.wan_addr == "" && mArray.openmptcprouter.wan_addr6 == "" && mArray.openmptcprouter.external_check == true)
					{
						statusMessage += '<%:No public IP address detected in less than 1 second%>' + '<br/>';
					}
					if (mArray.openmptcprouter.vps_admin == false)
					{
						statusMessage += '<%:Can\'t contact Server Admin Script%>';
						if (mArray.openmptcprouter.vps_admin_error_msg !== "")
						{
							statusMessage += ' <i>(' + mArray.openmptcprouter.vps_admin_error_msg + ')</i>';
						}
						statusMessage += '<br/>';
					} 
					if (mArray.openmptcprouter.vps_mptcp == "0")
					{
						statusMessage += '<%:MPTCP is not enabled on the server%>' + '<br/>';
					} 
					if (mArray.openmptcprouter.vps_time_accurate == false)
					{
						var vps_time = new Date(mArray.openmptcprouter.vps_time*1000).toISOString();
						var omr_time = new Date(mArray.openmptcprouter.omr_time*1000).toISOString();
						statusMessage += '<%:Big time difference between the server and the router%> (' + vps_time + '/' + omr_time + ') <br/>';
					}
				}
				if (statusMessage !== "" && statusMessageClass !== "error")
				{
					statusMessageClass = "warning";
					statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
				}
				if (mArray.openmptcprouter.vps_omr_version)
				{
					content += '<%:Version%>' + " " + mArray.openmptcprouter.vps_omr_version;
					if (mArray.openmptcprouter.vps_kernel)
					{
						content += " " + mArray.openmptcprouter.vps_kernel;
					}
					if (mArray.openmptcprouter.latest_version_vps !== mArray.openmptcprouter.vps_omr_version && mArray.openmptcprouter.latest_version_vps !== "")
					{
						content += "<br><i>(" + '<%:Latest available version%>' + " " + mArray.openmptcprouter.latest_version_vps + ")</i>";
					}
					content += "<br />";
				}
				if (mArray.openmptcprouter.vps_loadavg)
				{
					content += '<%:Load:%>' + " " + mArray.openmptcprouter.vps_loadavg;
					content += "<br />";
				}
				if (mArray.openmptcprouter.vps_uptime)
				{
					var date = new Date(null);
					content += '<%:Uptime:%>' + " " + String.format('%t', mArray.openmptcprouter.vps_uptime);
					content += "<br />";
				}
				if (mArray.openmptcprouter.server_mptcp == "disabled")
				{
					statusMessage += '<%:MPTCP may not be enabled on the server%>' + '<br/>';
					statusMessageClass = "warning";
					statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
				}
				if (mArray.openmptcprouter.wan_addr6)
				{
					content += '<%:IPv6:%>' + " " + mArray.openmptcprouter.wan_addr6;
					content += '<br />';
				}
				if (mArray.openmptcprouter.proxy_traffic && mArray.openmptcprouter.proxy_traffic != 0)
				{
					content += '<%:Proxy traffic:%>' + " " + formatBytes(mArray.openmptcprouter.proxy_traffic);
					content += '<br />';
				}
				if (mArray.openmptcprouter.vpn_traffic && mArray.openmptcprouter.vpn_traffic != 0)
				{
					content += '<%:VPN traffic:%>' + " " + formatBytes(mArray.openmptcprouter.vpn_traffic);
					content += '<br />';
				}
				if (mArray.openmptcprouter.total_traffic && mArray.openmptcprouter.total_traffic != 0)
				{
					content += '<%:Total traffic:%>' + " " + formatBytes(mArray.openmptcprouter.total_traffic);
					content += '<br />';
				}
				content += '<br />';

				temp += getNetworkNodeTemplate(equipmentIcon, statusIcon, title, statusMessageClass,statusMessage,content);
				temp += '</a></td></tr></table>';
				temp += '</td>';
			}
			if (mArray !== null && (mArray.wans || mArray.tunnels))
			{
				temp += '<td><ul>';
				var master = 0;
				for( var i = 0; i < mArray.wans.length; i++ )
				{
					// Get link color
					mArray.wans[i].color = stringToColour(mArray.wans[i].name)
					// Mwan status infos and colors
					var stat = '';
					var cssc = '';
					switch (mArray.wans[i].status)
					{
						case 'OK':
							stat = 'Online';
							cssc = 'rgb(144, 240, 144)';
							statusIcon = "<%=resource%>/openmptcprouter/images/statusOK.png";
							statusMessageClass = "";
							statusMessage = "";
							break;
						case 'ERROR':
							stat = 'Offline';
							cssc = 'rgb(240, 144, 144)';
							statusIcon = "<%=resource%>/openmptcprouter/images/statusError.png";
							statusMessageClass = "error";
							statusMessage = "";
							break;
						default:
							stat = 'Unknown';
							cssc = 'rgb(144, 240, 144)';
							statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
							statusMessageClass = "warning";
							statusMessage = "";
					}
					// Populate info
					var wanip    = mArray.wans[i].wanip;
					if (anonymize == "true" && testPrivateIP(wanip) == false)
					{
						wanip=replaceLastNChars(wanip,"x",6);
					}
					var wanip6   = mArray.wans[i].wanip6;
					if (anonymize == "true")
					{
						wanip6=replaceLastNChars(wanip6,"x",6);
					}
					var ipaddr    = mArray.wans[i].ipaddr;
					if (anonymize == "true" && testPrivateIP(ipaddr) == false)
					{
						ipaddr=replaceLastNChars(ipaddr,"x",6);
					}
					var ip6addr   = mArray.wans[i].ip6addr;
					if (anonymize == "true")
					{
						ip6addr=replaceLastNChars(ip6addr,"x",6);
					}
					var ifname    = mArray.wans[i].ifname;
					var iftype    = mArray.wans[i].iftype;
					var whois     = mArray.wans[i].whois;
					var whois6    = mArray.wans[i].whois6;
					var signal    = mArray.wans[i].signal;
					var istatus    = mArray.wans[i].status;
					var multipath = mArray.wans[i].multipath;
					if(multipath == 'master')
					{
						master++;
					}
					var zonewan = mArray.wans[i].zonewan;
					var latency = mArray.wans[i].latency;
					var mtu = mArray.wans[i].mtu;
					var operator = mArray.wans[i].operator;
					var phonenumber = mArray.wans[i].phonenumber;
					var donglestate = mArray.wans[i].donglestate;
					var networktype = mArray.wans[i].networktype;
					var gateway = mArray.wans[i].gateway;
					if (anonymize == "true" && testPrivateIP(gateway) == false)
					{
						gateway=replaceLastNChars(gateway,"x",6);
					}
					var gateway6 = mArray.wans[i].gateway6;
					if (anonymize == "true" && testPrivateIP(gateway6) == false)
					{
						gateway6=replaceLastNChars(gateway6,"x",10);
					}
					var gw_ping = mArray.wans[i].gw_ping;
					var gw_ping6 = mArray.wans[i].gw_ping6;
					var server_ping = mArray.wans[i].server_ping;
					var server_http = mArray.wans[i].server_http;
					var ipv6_discover = mArray.wans[i].ipv6_discover;
					var multipath_available = mArray.wans[i].multipath_available;
					var multipath_state = mArray.wans[i].multipath_state;
					var duplicateif = mArray.wans[i].duplicateif;
					var duplicatemac = mArray.wans[i].duplicatemac;
					var loop = mArray.wans[i].loop;
					// Generate template
					if(mArray.openmptcprouter.remote_from_lease == true && mArray.wans.length == 1)
					{
						temp += String.format('<li class="subnode-only-child"><a href="%q">', mArray.wans[i].link);
					} else {
						temp += String.format('<li><a href="%q">', mArray.wans[i].link);
					}

					var equipmentIcon = String.format('<embed id="modem_%s" onload="setColorSVG(\'modem_%s\', \'%s\')" src="<%=resource%>/modem.svg" />', mArray.wans[i].name, mArray.wans[i].name, mArray.wans[i].color);
					if (mArray.wans[i].gateway !== "")
					{
						var title = mArray.wans[i].label + " (" + gateway + ")";
					} else if (mArray.wans[i].gateway6 !== "")
					{
						var title = mArray.wans[i].label + " (" + gateway6 + ")";
					} else {
						var title = mArray.wans[i].label;
					}
					var content = "";
					if(ipaddr !== '')
					{
						content += String.format('%s <strong>%s</strong><br />','<%:ip address:%>', ipaddr);
					}
					if(ip6addr !== '' && gateway6 !== '')
					{
						content += String.format('%s <strong>%s</strong><br />','<%:ipv6 address:%>', ip6addr);
					}
					if(wanip !== '')
					{
						content += String.format('%s <strong>%s</strong><br />','<%:wan address:%>', wanip);
					}
					if(wanip6 !== '')
					{
						content += String.format('%s <strong>%s</strong><br />','<%:wan ipv6 address:%>', wanip6);
					}
					if(ifname !== '' && ifname !== mArray.wans[i].label)
					{
						content += String.format('%s %s<br />','<%:interface:%>', ifname);
					}
					if(whois !== '')
					{
						content += String.format('%s %s<br />','<%:whois:%>', whois);
					}
					if(whois6 !== '' && whois6 != whois)
					{
						content += String.format('%s %s<br />','<%:whois:%>', whois6);
					}
					if(latency !== '')
					{
						content += String.format('%s %s ms<br />','<%:latency:%>', latency);
					}
					if(mtu !== '')
					{
						content += String.format('%s %s<br />','<%:mtu:%>', mtu);
					}
					if (operator !== '')
					{
						content += String.format('%s %s<br />','<%:operator:%>', operator);
					}
					if (phonenumber !== '' && anonymize !== 'true')
					{
						content += String.format('%s %s<br />','<%:phone number:%>', phonenumber);
					}
					if (donglestate !== '')
					{
						content += String.format('%s %s<br />','<%:state:%>', donglestate);
					}

					if(signal !== '')
					{
						if (signal <= 0)
							title += ' <img src="/luci-static/resources/icons/signal-0.png" />';
						else if (signal < 25)
							title += ' <img src="/luci-static/resources/icons/signal-0-25.png" />';
						else if (signal < 50)
							title += ' <img src="/luci-static/resources/icons/signal-25-50.png" />';
						else if (signal < 75)
							title += ' <img src="/luci-static/resources/icons/signal-50-75.png" />';
						else 
							title += ' <img src="/luci-static/resources/icons/signal-75-100.png" />';
					}
					if (networktype !== '')
					{
						title += String.format(' <i>%s</i>',networktype);
					}
					if(ipaddr == '' && ip6addr == '')
					{
						statusMessage += '<%:No IP defined%>' + '<br />';
					}
					if(gateway == '' && gateway6 == '')
					{
						statusMessage += '<%:No gateway defined%>' + '<br />';
					} else if(gateway != '' && gw_ping == 'DOWN')
					{
						statusMessage += '<%:Gateway DOWN%>' + '<br />';
					} else if(gateway6 != '' && gw_ping6 == 'DOWN')
					{
						statusMessage += '<%:Gateway IPv6 DOWN%>' + '<br />';
					} else if(multipath_available == 'ERROR')
					{
						statusMessage += '<%:Multipath seems to be blocked on the connection%>' + '<br />';
					}
					if(server_ping == 'DOWN' && mArray.openmptcprouter.service_addr !== "")
					{
						statusMessage += '<%:No Server ping response after 1 second%>' + '<br />';
					}
					if(server_http == 'DOWN' && mArray.openmptcprouter.service_addr !== "")
					{
						statusMessage += '<%:No Server http response after 1 second%>' + '<br />';
					}
					if(zonewan == "NO")
					{
						statusMessage += '<%:Network interface not in WAN firewall zone%>' + '<br />';
						statusMessageClass = "warning";
					}
					if (istatus == 'ERROR' && ipaddr != '' && ipaddr == mArray.wans[i].gateway)
					{
						statusMessage += '<%:Wan IP and gateway are identical%>' + '<br />';
						statusMessageClass = "error";
					}
					if (istatus == 'ERROR' && ip6addr != '' && ip6addr == mArray.wans[i].gateway6)
					{
						statusMessage += '<%:Wan IP and gateway are identical%>' + '<br />';
						statusMessageClass = "error";
					}
					if(multipath == 'master') 
					{
						if (master > 1)
						{
							statusMessage += '<%:Multipath master already defined%>' + '<br />';
							statusMessageClass = "error";
						}
						if(multipath_state !== 'on' && multipath_state !== '')
						{
							statusMessage += '<%:Multipath current state is %>' + multipath_state + '<br />';
							statusMessageClass = "error";
						}
					} else {
						if(multipath !== multipath_state && multipath_state !== '')
						{
							statusMessage += '<%:Multipath current state is %>' + multipath_state + '<br />';
							statusMessageClass = "error";
						}
					}
					if(duplicateif)
					{
						statusMessage += '<%:Network interface duplicated%>' + '<br />';
						statusMessageClass = "error";
					}
					if(iftype == "bridge")
					{
						statusMessage += '<%:Bridge can't have multipath enabled%>' + '<br />';
						statusMessageClass = "error";
					}
					if(duplicatemac)
					{
						statusMessage += '<%:Network interface MAC address duplicated%>' + '<br />';
						statusMessageClass = "error";
					}
					if(loop)
					{
						statusMessage += '<%:Looping route detected%>' + '<br />';
					}
					if(ipv6_discover == 'DETECTED')
					{
						statusMessage += '<%:IPv6 route received%>' + '<br />'
					}
					if (statusMessage !== "" && statusMessageClass !== "error")
					{
						statusMessageClass = "warning";
						statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
					}
					if (statusMessage !== "" && statusMessageClass == "error")
					{
						statusMessageClass = "error";
						statusIcon = "<%=resource%>/openmptcprouter/images/statusError.png";
					}
					content += String.format('<%:multipath:%> %s<br />',multipath);
					if(mArray.wans[i].qos && mArray.wans[i].download > 0 && mArray.wans[i].upload > 0)
					{
						content += String.format('%s %s/%s kbps (%s)','<%:traffic control:%>', mArray.wans[i].download, mArray.wans[i].upload, mArray.wans[i].qos)
					}
					temp += getNetworkNodeTemplate(equipmentIcon, statusIcon, title, statusMessageClass,statusMessage,content);

					temp += '</a></li>';
				}
				if (mArray.wans.length == 0)
				{
					temp += '<li>';
					temp += '<%:No WAN with multipath enabled:%>';
					temp += '</li>';
				}
				for( var i = 0; i < mArray.tunnels.length; i++ )
				{
					// Get link color
					mArray.tunnels[i].color = stringToColour(mArray.tunnels[i].name)
					// Mwan status infos and colors
					var stat = '';
					var cssc = '';
					switch (mArray.tunnels[i].status)
					{
						case 'OK':
							stat = 'Online';
							cssc = 'rgb(144, 240, 144)';
							statusIcon = "<%=resource%>/openmptcprouter/images/statusOK.png";
							statusMessageClass = "";
							statusMessage = "";
							break;
						case 'ERROR':
							stat = 'Offline';
							cssc = 'rgb(240, 144, 144)';
							statusIcon = "<%=resource%>/openmptcprouter/images/statusError.png";
							statusMessageClass = "error";
							statusMessage = "";
							break;
						default:
							stat = 'Unknown';
							cssc = 'rgb(144, 240, 144)';
							statusIcon = "<%=resource%>/openmptcprouter/images/statusWarning.png";
							statusMessageClass = "warning";
							statusMessage = "";
					}
					// Populate info
					var wanip   = mArray.tunnels[i].wanip;
					if (anonymize == "true" && testPrivateIP(wanip) == false)
					{
						wanip=replaceLastNChars(wanip,"x",6);
					}
					var ipaddr   = mArray.tunnels[i].ipaddr;
					if (anonymize == "true" && testPrivateIP(ipaddr) == false)
					{
						ipaddr=replaceLastNChars(ipaddr,"x",6);
					}
					var whois   = mArray.tunnels[i].whois;
					var multipath = mArray.tunnels[i].multipath;
					if(multipath == 'master')
					{
						master++;
					}
					var latency = mArray.tunnels[i].latency;
					var mtu = mArray.tunnels[i].mtu;
					var gateway = mArray.tunnels[i].gateway;
					if (anonymize == "true" && testPrivateIP(gateway) == false)
					{
						gateway=replaceLastNChars(gateway,"x",6);
					}
					var gw_ping = mArray.tunnels[i].gw_ping;
					var server_ping = mArray.tunnels[i].server_ping;
					var ipv6_discover = mArray.tunnels[i].ipv6_discover;
					var multipath_available = mArray.tunnels[i].multipath_available;
					var multipath_state = mArray.tunnels[i].multipath_state;
					var duplicateif = mArray.tunnels[i].duplicateif;
					// Generate template
					if(mArray.openmptcprouter.remote_from_lease == true && mArray.tunnels.length == 1)
					{
						temp += String.format('<li class="subnode-only-child"><a href="%q">', mArray.tunnels[i].link);
					} else {
						temp += String.format('<li><a href="%q">', mArray.tunnels[i].link);
					}

					var equipmentIcon = String.format('<embed id="modem_%s" onload="setColorSVG(\'modem_%s\', \'%s\')" src="<%=resource%>/modem.svg" />', mArray.tunnels[i].name, mArray.tunnels[i].name, mArray.tunnels[i].color);
					if (mArray.tunnels[i].gateway !== "")
					{
						var title = mArray.tunnels[i].label + " (" + gateway + ")";
					} else {
						var title = mArray.tunnels[i].label;
					}
					var content = "";
					if(ipaddr !== '')
					{
						content += String.format('%s <strong>%s</strong><br />','<%:ip address:%>', ipaddr);
					}
					if(wanip !== '')
					{
						content += String.format('%s <strong>%s</strong><br />','<%:wan address:%>', wanip);
					}
					if(whois !== '')
					{
						content += String.format('%s %s<br />','<%:whois:%>', whois);
					}
					if(latency !== '')
					{
						content += String.format('%s %s ms<br />','<%:latency:%>', latency);
					}
					if(mtu !== '')
					{
						content += String.format('%s %s<br />','<%:mtu:%>', mtu);
					}
					if(ipaddr == '')
					{
						statusMessage += '<%:No IP defined%>' + '<br />'
					}
					if(gateway == '')
					{
						statusMessage += '<%:No gateway defined%>' + '<br />'
					} else if(gw_ping == 'DOWN')
					{
						statusMessage += '<%:Gateway DOWN%>' + '<br />'
					} else if(multipath_available == 'ERROR')
					{
						statusMessage += '<%:Multipath seems to be blocked on the connection%>' + '<br />'
					}
					if(server_ping == 'DOWN')
					{
						statusMessage += '<%:No Server ping response after 1 second%>' + '<br />'
					}
					if (stat == 'Offline' && ipaddr != '' && ipaddr == mArray.tunnels[i].gateway)
					{
						statusMessage += '<%:Wan IP and gateway are identical%>' + '<br />';
						statusMessageClass = "error";
					}
					if(multipath == 'master') 
					{
						if (master > 1)
						{
							statusMessage += '<%:Multipath master already defined%>' + '<br />';
							statusMessageClass = "error";
						}
						if(multipath_state !== 'on' && multipath_state !== '')
						{
							statusMessage += '<%:Multipath current state is %>' + multipath_state + '<br />';
							statusMessageClass = "error";
						}
					} else {
						if(multipath !== multipath_state && multipath_state !== '')
						{
							statusMessage += '<%:Multipath current state is %>' + multipath_state + '<br />';
							statusMessageClass = "error";
						}
					}
					if(duplicateif)
					{
						statusMessage += '<%:Network interface duplicated%>' + '<br />';
						statusMessageClass = "error";
					}
					if(ipv6_discover == 'DETECTED')
					{
						statusMessage += '<%:IPv6 route received%>' + '<br />'
					}
					content += String.format('<%:multipath:%> %s<br />',multipath);
					if(mArray.tunnels[i].qos && mArray.tunnels[i].download > 0 && mArray.tunnels[i].upload > 0)
					{
						content += String.format('%s %s/%s kbps (%s)','<%:traffic control:%>', mArray.tunnels[i].download, mArray.tunnels[i].upload, mArray.tunnels[i].qos)
					}
					temp += getNetworkNodeTemplate(equipmentIcon, statusIcon, title, statusMessageClass,statusMessage,content);

					temp += '</a></li>';
				}
				temp += '</ul></td>';
				temp += '</tr></table>';
			}
			if (mArray === null) {
			    temp += '<%:No data%>';
			}
			temp += '</li>';
			// Close tree
			temp += '</ul>';
			temp += '</figure>';
			status.innerHTML = temp;
		}
	);

	function setColorSVG(embed_id, color)
	{
		var embed = document.getElementById(embed_id);
		try {
			svg = embed.getSVGDocument ? embed.getSVGDocument() : embed.contentDocument;
		}
		catch(e) {
			svg = document.embeds[embed_id].getSVGDocument();
		}
		if(svg)
		{
			var back = svg.getElementById('backgound_modem');
			back.setAttribute('style', 'fill: ' + color + ';fill-opacity:0.6;');
		}
	}

	function getNetworkNodeTemplate(equipmentIcon, statusIcon, title, statusMessageClass, statusMessage, content)
	{
		return String.format('<div class="network-node">' +
						'<div class="equipment-icon">%s</div>' +
						'<div class="status-icon"><img src="%s" /></div>' +
						'<div class="info">' +
							'<div class="title">%s</div>' +
							'<div class="status-message %s">%s</div>' +
							'<div class="content">%s</div>' +
							'<div class="clear"></div>' +
						'</div>' +
						'<div class="clear"></div>' +
					'</div>',
					equipmentIcon, statusIcon, title, statusMessageClass, statusMessage, content);
	}

	function stringToColour(str) {
		if(str == "wan1")
			return "BlueViolet";
		if(str == "wan2")
			return "DeepSkyBlue";
		if(str == "wan3")
			return "LightGreen";
		if(str == "wan4")
			return "PowderBlue";
		if(str == "wan5")
			return "PaleGreen";
		if(str == "wan6")
			return "YellowGreen";
		if(str == "wan7")
			return "SeaGreen";
		if(str == "wan8")
			return "SteelBlue";

		// Generate a color folowing the name
		Math.seedrandom(str);
		var rand = Math.random() * Math.pow(255,3);
		Math.seedrandom(); // don't leave a non-random seed in the generator
		for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((rand >> i++ * 8) & 0xFF).toString(16)).slice(-2));
		return colour;
	}

	function setAnonymize(data)
	{
		document.cookie="anonymize=" + data.checked + "; path=/cgi-bin/luci/";
		location.reload();
	}

	var replaceLastNChars = function(str, replace, num) {
		if (str == "") return str;
		return str.slice(0, -num) + Array(num + 1).join(replace);
	};
//]]></script>

<h2><%:Network overview%></h2>
<fieldset id="interface_field" class="cbi-section">
	<!--	<legend><%:Network overview%></legen> -->
	<div id="openmptcprouter_status"><img src="<%=resource%>/spinner.gif" /></div>
</fieldset>
<form class="inline">
	<div class="cbi-map">
		<h3>Settings</h3>
		<fieldset class="cbi-section">
			<div class="cbi-value">
				<label class="cbi-value-title">Anonymize public IPs</label>
				<div class="cbi-value-field">
					<input type="checkbox" name="anon" id="anon" class="cbi-input-checkbox" value="1" onclick="setAnonymize(this)" \>
				</div>
			</div>
		</fieldset>
	</div>
</form>
<%+footer%>